import { type EditPhoneRequest, SmsType, editPhoneAxios, sendAuthCodeByPhoneAxios, sendAuthCodeByUserAxios } from '@/api/login';
import { getPhoneRules, getSmsCodeRules } from '@/utils/page/rules';
import type { FormRules } from 'element-plus';
/** 修改手机号 */
export function useEditPhone() {
  const editPhoneFormRef: $RefComp<'ElForm'> = ref(null);
  const oldEditPhoneCountDownRef: $RefComp<'BaseCountDownButton'> = ref(null);
  const newEditPhoneCountDownRef: $RefComp<'BaseCountDownButton'> = ref(null);
  const phoneLoading = ref(false);
  const { phoneRules } = getPhoneRules();
  const { smsCodeRules } = getSmsCodeRules();
  const editPhoneRules: FormRules<EditPhoneRequest> = {
    smsCode: smsCodeRules,
    newPhone: phoneRules,
    newSmsCode: smsCodeRules,
  };
  const editPhoneForm: EditPhoneRequest = reactive({
    smsCode: '',
    newPhone: '',
    newSmsCode: '',
  });
  /** 发送验证码(原手机验证码) */
  async function oldEditPhoneSendSmsCode() {
    try {
      oldEditPhoneCountDownRef.value?.setLoadState(true);
      await sendAuthCodeByUserAxios(SmsType.AppSMSChangeBindOldPhone);
      oldEditPhoneCountDownRef.value?.setLoadState(false);
      oldEditPhoneCountDownRef.value?.start(); // 开始倒计时
    } catch (err) {
      oldEditPhoneCountDownRef.value?.setLoadState(false);
      ElToast.error(err.msg || '验证码发送失败');
    }
  }

  /** 发送验证码(新手机验证码) */
  async function newEditPhoneSendSmsCode() {
    try {
      await editPhoneFormRef.value?.validateField('newPhone');
      try {
        newEditPhoneCountDownRef.value?.setLoadState(true);
        await sendAuthCodeByPhoneAxios(SmsType.AppSMSChangeBindNewPhone, editPhoneForm.newPhone);
        newEditPhoneCountDownRef.value?.setLoadState(false);
        newEditPhoneCountDownRef.value?.start(); // 开始倒计时
      } catch (err) {
        newEditPhoneCountDownRef.value?.setLoadState(false);
        ElToast.error(err.msg || '验证码发送失败');
      }
    } catch (error) {}
  }

  /** 修改手机号 */
  async function submitEditPhone() {
    try {
      await editPhoneFormRef.value?.validate();
      try {
        phoneLoading.value = true;
        await editPhoneAxios({ newPhone: editPhoneForm.newPhone, smsCode: editPhoneForm.smsCode, newSmsCode: editPhoneForm.newSmsCode });
        phoneLoading.value = false;
        useUserStore().logout(false);
        ElToast.success('修改成功');
      } catch (error) {
        phoneLoading.value = false;
        ElToast.error(error.msg || '提交失败，-BD003');
      }
    } catch (error) {
      ElToast.error('提交失败，请完善表单，-BD001');
    }
  }
  return {
    editPhoneRules,
    editPhoneFormRef,
    oldEditPhoneCountDownRef,
    newEditPhoneCountDownRef,
    phoneLoading,
    editPhoneForm,
    submitEditPhone,
    newEditPhoneSendSmsCode,
    oldEditPhoneSendSmsCode,
  };
}
